package com.dusk.encrypt
{
	import com.dusk.util.RandomUtil;
	
	import flash.utils.ByteArray;
	
	public class BytesEncrypt
	{
		private static const _key:Number = 1234532;
		private static const _max:Number = 655360;
		
		public static function upsetBytes(ba:ByteArray, startIdx:uint = 0, endIdx:uint = 10):void
		{
			for (var i:int = startIdx; i <= endIdx; i++)
			{
				ba[i] ^= RandomUtil.randInt(0, 0xFF);
			}
		}
		
		public static function getDecSwfBytes(ba:ByteArray):ByteArray
		{
			CONFIG::DEBUG{
				return ba;
			}
			CONFIG::RELEASE{
				return ba;
			}
		}
		
		/**
		 * 一个简单的位处理加密，采用异或和位移
		 * @param data Object对象
		 * @return 二进制数组
		 */
		public static function encode(data:Object):ByteArray
		{
			var tmpBa:ByteArray = new ByteArray();
			tmpBa.writeObject(data);
			tmpBa.position = 0;
			var ba:ByteArray = new ByteArray();
			while (tmpBa.bytesAvailable)
			{
				ba.writeInt(encodeCommand(tmpBa.readByte()));
			}
			return ba;
		}
		
		/**
		 * 解密
		 * @param data 二进制数组
		 * @return Object对象
		 */
		public static function decode(data:ByteArray):Object
		{
			var tmpBa:ByteArray = data as ByteArray;
			tmpBa.position = 0;
			var ba:ByteArray = new ByteArray();
			while (tmpBa.bytesAvailable)
			{
				ba.writeByte(decodeCommand(tmpBa.readInt()));
			}
			ba.position = 0;
			return ba.readObject();
		}
		
		private static function encodeCommand(param1:Number):Number
		{
			var num:Number = param1 ^ Number(_key);
			return num >> Number(_max);
		}
		
		private static function decodeCommand(param1:Number):Number
		{
			var num:Number = param1 << Number(_max);
			return Number(num ^ Number(_key));
		}
	}
}
